package com.spring.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.spring.adapter.LocationAdapter;
import com.spring.gowhere.R;
import com.spring.httputils.RequestParams;
import com.spring.httputils.RestClient;
import com.spring.httputils.TextHttpResponseHandler;
import com.spring.model.ReturnLoanAccount;
import com.spring.tool.App;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Map;

/**
 * 收支分析
 * 
 * @author Administrator
 * 
 */
public class AceActivity extends BaseActivity {

	private static final int SERIES_NR = 3;
	/** Called when the activity is first created. */
	private ArrayList<Map<String, String>> maps = new ArrayList<Map<String, String>>();
	RestClient restClient = null;
	private String username, logintype;
	ReturnLoanAccount account = null;
	private boolean isData = false;
	 RelativeLayout location;
	private TextView location_text;
	private String location_textStr;
	public String type = "1";

	LinearLayout myLayout;
	CategorySeries categorySeries;
	GraphicalView pieChart = null;
	GraphicalView pieChartTemp = null;
	DefaultRenderer renderer = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aceactivity);
		ImageButton imageButton = (ImageButton) findViewById(R.id.title_left_ib);
		imageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		myLayout = (LinearLayout) findViewById(R.id.acelineaylayouts); // myLayout是我这个activity的界面的root
		TextView textView = (TextView) findViewById(R.id.title_tv);
		textView.setText("收支分析");
		SharedPreferences userInfo = getSharedPreferences("user_info", 0);
		username = userInfo.getString("username", "");
		logintype = userInfo.getString("logintype", "");
		location = (RelativeLayout) findViewById(R.id.reservation_location);
		location_text = (TextView) findViewById(R.id.reservation_location_text);
		location.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new LocationDialog(AceActivity.this).show();
			}
		});
		if (type != null) {
			restClient = new RestClient(AceActivity.this);
			SendHttpData();
		}

	}

	// 设置饼状图
	public GraphicalView execute(Context context) {
		int[] colors = new int[] { Color.RED, Color.YELLOW, Color.BLUE,
				Color.CYAN };
		renderer = buildCategoryRenderer(colors);
		categorySeries = new CategorySeries("Vehicles Chart");
		categorySeries.add("现金充值", account.getCashMoney());
		categorySeries.add("补助充值", account.getSubsidyMoney());
		categorySeries.add("提款金额", account.getDrawMoney());
		categorySeries.add("消费金额", account.getXFMoney());
		renderer.setZoomButtonsVisible(true);
		renderer.setZoomEnabled(true);

		GraphicalView view = ChartFactory.getPieChartView(context,
				categorySeries, renderer);
		return view;
	}

	protected DefaultRenderer buildCategoryRenderer(int[] colors) {
		DefaultRenderer renderer = new DefaultRenderer();
		for (int color : colors) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(color);
			renderer.addSeriesRenderer(r);
		}
		// 显示标签
		renderer.setShowLabels(true);
		// 不显示底部说明
		renderer.setShowLegend(false);
		// 设置标签字体大小
		renderer.setLabelsTextSize(24f);
		renderer.setLabelsColor(Color.BLACK);
		renderer.setZoomEnabled(false);
		renderer.setPanEnabled(false);
		return renderer;
	}

	/**
	 * 体检地点选择对话框
	 * 
	 * @author Administrator
	 * 
	 */
	private String[] locations = { "三个月", "半年", "一年", "开卡以来" };

	public class LocationDialog extends Dialog {

		public LocationDialog(Context context) {
			super(context, R.style.myDialog);
			// TODO Auto-generated constructor stub
		}

		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.indicatorsdialog);
			DisplayMetrics dm = new DisplayMetrics();
			Window window = getWindow();
			// 取得窗口属性
			window.getWindowManager().getDefaultDisplay().getMetrics(dm);
			// 屏幕的宽度
			int screenWidth = dm.widthPixels;
			WindowManager.LayoutParams wl = window.getAttributes();
			wl.width = screenWidth - dip2px(this.getContext(), 30);
			window.setAttributes(wl);

			ListView listview = (ListView) findViewById(R.id.indicators_list);
			LocationAdapter adapter = new LocationAdapter(AceActivity.this, "0");
			adapter.setLocation(locations);
			listview.setAdapter(adapter);
			listview.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long i) {
					location_text.setText(locations[position]);
					location_textStr = locations[position];
					switch (position) {
					case 0:
						type = "1";
						SendHttpData();
						break;
					case 1:
						type = "2";
						SendHttpData();
						break;
					case 2:
						type = "3";
						SendHttpData();
						break;
					case 3:
						type = "4";
						SendHttpData();
					default:
						break;

					}

					dismiss();
				}
			});
		}

	}

	/**
	 * dip变pix公式
	 * 
	 * @param context
	 * @param dipValue
	 * @return
	 */
	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public void SendHttpData() {
		String url = App.getInstance().url + "/QueryLoanAccount";
		Log.e("sdfsdf", "abcxxq---+"+App.getInstance().url);
		RequestParams requestparams = new RequestParams(url, "POST");
		requestparams.put("LoginAccount", username);
		requestparams.put("LoginType", logintype);
		requestparams.put("SelectType", type);
		TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String responseString) {
				// TODO Auto-generated method stub
				Log.e("TAG", "responseString---" + responseString);
				try {
					if(responseString!=null&&!"".equals(responseString)){						
						AnalysisData(responseString);
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				Log.e("TAG", "responseString---" + responseString);

			}
		};
		try {
			restClient.post(url, requestparams, textHttpResponseHandler);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * json数据解析
	 * 
	 * @param strResult
	 * @throws JSONException
	 */
	private void AnalysisData(String strResult) throws JSONException {
		/**
		 * 这里需要分析服务器回传的json格式数据，
		 */
		JSONObject jsonObject = new JSONObject(strResult);
		account = new ReturnLoanAccount();
		account.setCashMoney(jsonObject.getDouble("CashMoney"));
		account.setSubsidyMoney(jsonObject.getDouble("SubsidyMoney"));
		account.setDrawMoney(jsonObject.getDouble("DrawMoney"));
		account.setSaveMoney1(jsonObject.getDouble("SaveMoney1"));
		account.setSaveMoney2(jsonObject.getDouble("SaveMoney2"));
		account.setXFMoney(jsonObject.getDouble("XFMoney"));
		account.setReservedField1(jsonObject.getString("ReservedField1"));
		account.setReservedField2(jsonObject.getString("ReservedField2"));

		pieChartTemp = pieChart;
		pieChart = execute(AceActivity.this);
		if (pieChartTemp != null) {
			myLayout.removeView(pieChartTemp);
		}
		
		myLayout.addView(pieChart, new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

	}
}